'use strict';

//引入模块的属性
const { Sequelize, DataTypes } = require('sequelize');
const { database, role, pws, host, dialect } = require('./config');


//要连接到数据库,必须创建一个 Sequelize 实例. 
// 这可以通过将连接参数分别传递到 Sequelize 构造函数或通过传递一个连接 URI 来完成：
const sequelize = new Sequelize(database, role, pws, {
    host: host,
    dialect: dialect
})


//创建函数，包装模型
function defineModel(name, attrs) {

    let obj = {
        id: {
            type: DataTypes.BIGINT,
            primaryKey: true,   //主键       
            autoIncrement: true  //自增
        },
    };

    for (var key in attrs) {
        let value = attrs[key];
        obj[key] = value
    }

    //添加创建时间属性
    obj.createdAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    };

    //添加更改时间属性
    obj.updatedAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    };

    //添加版本属性
    obj.version = {
        type: DataTypes.BIGINT,
        allowNull: false
    };

    //添加备注属性
    obj.remarks = {
        type: DataTypes.STRING(800),
        allowNull: true
    };

    //利用sequelize实例一个模型
    let models = sequelize.define(name, obj, {
        tableName: name,
        timestamps: false,  //不自动添加updatedAt,createdAt字段

        //钩子对象
        hooks: {
            beforeValidate(obj) {

                //获取时间戳
                let now = Date.now();

                if (obj.isNewRecord) {
                    obj.createdAt = now;
                    obj.updatedAt = now;
                    obj.version = 0;
                } else {
                    obj.updatedAt = now;
                    obj.version += 1;
                }
            }
        }
    })

    return models;

}


module.exports = {
    defineModel,
    DataTypes,
    sequelize
}